package com.my.main.component.init;

import com.my.main.component.interceptor.ApiPermissionInterceptor;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * spring初始化
 *
 * @author mengft 2020-07-20
 */
@Component
public class MyCommandLineRunner implements CommandLineRunner {


    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private ApiPermissionInterceptor apiPermissionInterceptor;


    @Override
    public void run(String... args) throws Exception {
        /************************ 实现添加路由白名单 mengft 2020-07-20 start *****************************/
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        List<String> apiWhiteList = new ArrayList<>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> mapEntry : map.entrySet()) {
            RequestMappingInfo info = mapEntry.getKey();
            HandlerMethod method = mapEntry.getValue();

            // 获取方法注解信息
            ApiOperation anno = method.getMethod().getAnnotation(ApiOperation.class);
            if (anno == null) {
                continue;
            }

            // 获取该方法是否是白名单
            if ("NOINTERCEPT".equals(anno.tags()[0])) {
                // 获取方法url
                PatternsRequestCondition p = info.getPatternsCondition();
                for (String url : p.getPatterns()) {
                    apiWhiteList.add(url);
                }
            }
        }

        // 把获取到的白名单传入过滤器中进行下一步处理
        apiPermissionInterceptor.setWhiteApiList(apiWhiteList);
        /************************ 实现添加路由白名单 mengft 2020-07-20 end *****************************/
    }


}